package com.linwen.excise.leetcode;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * @ClassName _56合并区间
 * @Description TODO
 * @Author zero
 * @DATE 2024/4/7 11:39 PM
 * @Version 1.0
 */
public class _56合并区间 {
    public static void main(String[] args) {
        int[][] meetings = {{1,3},{2,6},{8,10},{15,18}};
        for (int i = 0; i < meetings.length; i++) {
            System.out.println(meetings[i][0]+" "+meetings[i][1]);
        }
        int[][] merge = merge(meetings);
        System.out.println("=========");
        for (int i = 0; i < merge.length; i++) {
            System.out.println(merge[i][0]+" "+merge[i][1]);
        }
    }
    public  static int[][] merge(int[][] meetings) {
        Arrays.sort(meetings,(a,b)->a[0]-b[0]);
        ArrayList<int[]> list = new ArrayList<>();
        for (int i = 0; i < meetings.length; i++) {
            if(i==0){
                list.add(meetings[0]);
            }
            int[] ints = list.get(list.size() - 1);
            if(isOver(ints,meetings[i])){
                list.remove(list.size()-1);
                list.add(new int[]{ints[0],Math.max(ints[1], meetings[i][1])});
            }else {
                list.add(meetings[i]);
            }
        }
        int[][] result = new int[list.size()][2];
        for (int i = 0; i < list.size(); i++) {
            result[i] = list.get(i);
        }
        return result;
    }

    private static boolean isOver(int[] ints, int[] meeting) {
        return ints[1]>=meeting[0];
    }
}
